package com.demo.generic;

import java.lang.reflect.ParameterizedType;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by hunter
 *
 * @Description 服务
 */
public class Server {

    /**
     * handler 缓存
     */
    private ConcurrentHashMap<Class, Handler<?>> handlerMap = new ConcurrentHashMap<>();

    /**
     * 注册handler
     *
     * @param handler
     */
    public void registerHandler(Handler<?> handler) {
        handlerMap.put(getGenericClass(handler.getClass()), handler);
    }

    /**
     * 获取多应类型的handler
     *
     * @param request
     * @return
     */
    public Handler<?> getHandler(Class request) {
        return handlerMap.get(request);
    }

    /**
     * 处理对应类型
     *
     * @param obj
     */
    @SuppressWarnings("unchecked")
    public <T> void doHandler(T obj) {
        Handler<T> handler = (Handler<T>) getHandler(obj.getClass());
        if (handler != null) {
            handler.handler(obj);
        } else {
            System.out.println("no handler for obj : " + obj);
        }
    }

    /**
     * 即获取 Class<?> 中的 ?.class
     *
     * @param clazz
     * @return
     */
    private Class getGenericClass(Class<?> clazz) {
        return (Class) ((ParameterizedType) clazz.getGenericInterfaces()[0]).getActualTypeArguments()[0];
    }
}
